package com.niuwa.p2p.action.messagemanager;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.custservice.CustServiceUser;
import com.niuwa.p2p.entity.custservice.ImportCustRule;
import com.niuwa.p2p.entity.message.MsgTemplate;
import com.niuwa.p2p.opr.utils.SessionUtil;
import com.niuwa.p2p.service.custService.ICustServiceService;
import com.niuwa.p2p.service.custService.IImportCustRuleService;
import com.niuwa.p2p.service.filesystem.FileSystem;
import com.niuwa.p2p.service.messageTemplate.IMessageTemplateService;
import com.niuwa.p2p.vo.customerservice.CustomerServiceJobUserVo;
import com.opensymphony.xwork2.ActionContext;

/**
 * @author futianliang
 * @date 2015年4月14日
 */
public class TemplateAction extends JsonAction {
	private static final long serialVersionUID = -8900124777631535966L;
	/** 日志 */
	private static Logger logger = Logger.getLogger(MessageAction.class);
	@Autowired
	private IMessageTemplateService templateService;
	@Autowired
	private FileSystem fileSystem;

	private String tempNo;
	private String fileID;
	@Autowired
	private ICustServiceService service;

	public String getFileID() {
		return fileID;
	}

	public void setFileID(String fileID) {
		this.fileID = fileID;
	}

	public String getTempNo() {
		return tempNo;
	}

	public void setTempNo(String tempNo) {
		this.tempNo = tempNo;
	}

	/* *
	 * 跳转到发送信息列表
	 */
	@Action(value = "gotoMessageTemplateManage")
	public String gotoLoanClaimListManagePage() {
		return "messageTemplateManage";
	}

	/**
	 * 查询牛娃账户列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "messageTemplateList")
	public String messageTemplateList() throws Exception {
		setObjectReSult(queryPage());
		logger.info("messageTemplateList action execute success");
		return NONE;
	}

	private PageBean<MsgTemplate> queryPage() {

		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();
		if (paramMap.get("templateCondition") != null) {
			paramMap.put("templateCondition", String.valueOf(paramMap.get("templateCondition")).trim().replaceAll("%", "\\\\%").replaceAll("_", "\\\\_"));
		}
		if (paramMap.get("lastUpdateEndTime") != null && !StringUtil.isEmpty(String.valueOf(paramMap.get("lastUpdateEndTime")))) {
			paramMap.put("lastUpdateEndTime", String.valueOf(paramMap.get("lastUpdateEndTime")).trim() + " 23:59:59");
		}
		int totalCount = templateService.getMessageTemplateCount(paramMap);
		PageBean<MsgTemplate> page = new PageBean<MsgTemplate>(totalCount);
		// 当前页
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(templateService.getMessageTemplateList(paramMap));
		
		return page;
	}

	@SuppressWarnings("unchecked")
	@Action("importMessageTemplate")
	public String importMessageTemplate() {
		JsonResult results = new JsonResult();
		try {

			long userId = SessionUtil.getSessionUser().getId();
			String message = "";
			File file = fileSystem.getFile(fileID);
			// fileId取filePath
			Map<String, Object> map = templateService.produceTemplateByExcel(file.getAbsolutePath());
			if (map != null) {
				if (map.get("key") instanceof String) {
					message = (String) map.get("key");
				} else {
					templateService.addMessageTemplateBatch((List<MsgTemplate>) map.get("key"), userId);
					message = "success";
				}
			}
			results.setMsg(message);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			results.setMsg("导入失败");
			e.printStackTrace();
		} finally {

			setResult(results);
		}
		return NONE;
	}

	@Action("gotoTemplateUpload")
	public String gotoUploadFile() {
		return "templateUpload";
	}

	@Action("gotoTemplateDetailInfo")
	public String gotoTemplateDetailInfo() {
		MsgTemplate msgTemplate = templateService.selectByPrimaryKey(tempNo);
		// msgTemplate.setTempContent(templateService.fetchMessageTemplateContentByType(MessageTemplateEnum.getEnum(msgTemplate.getTempNo()),
		// null, null).get("content"));
		msgTemplate.setSendMethod(msgTemplate.getSendMethod().replaceAll("SMS", "短信").replaceAll("IN_MSG", "站内信").replaceAll("EMAIL", "邮件"));
		ActionContext context = ActionContext.getContext();
		context.put("msgTemplate", msgTemplate);
		return "templateDetailInfo";

	}

}
